package ginx

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"go-admin-server/common/assert"
	"go-admin-server/common/biz"
	"go-admin-server/common/errors"
	"strconv"
	"strings"
)

// Parse body json data to struct
func ParseJSON(c *gin.Context, obj interface{}) error {
	if err := c.ShouldBindJSON(obj); err != nil {
		return errors.Wrap400Response(err, fmt.Sprintf("Parse request json failed: %s", err.Error()))
	}
	return nil
}

// Get jwt token from header (Authorization: Bearer xxx)
func GetToken(c *gin.Context) string {
	var token string
	auth := c.GetHeader("Authorization")
	prefix := "Bearer "
	if auth != "" && strings.HasPrefix(auth, prefix) {
		token = auth[len(prefix):]
	}
	return token
}

// 获取查询参数中指定参数值，并转为int
func QueryInt(c *gin.Context, key string, defaultVal int) int {
	val := c.Query(key)
	if val == "" {
		return defaultVal
	}
	intVal, err := strconv.Atoi(val)
	assert.AssertErrIsNil(err, "query param is not number")
	return intVal
}

// 绑定并校验请求结构体参数  结构体添加 例如： binding:"required" 或binding:"required,gt=10"
func BindJsonAndValid(g *gin.Context, data interface{}) {
	if err := g.ShouldBindJSON(data); err != nil {
		panic(biz.NewBizErr("传参格式错误：" + err.Error()))
	}
}

func ShouldBind(g *gin.Context, data interface{}) {
	if err := g.ShouldBind(data); err != nil {
		panic(biz.NewBizErr("传参格式错误：" + err.Error()))
	}
}
